package com.hongtech.tiny.modules.gen.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hongtech.tiny.common.response.ObjectResult;
import com.hongtech.tiny.common.response.PageResult;
import com.hongtech.tiny.modules.gen.service.SysGeneratorService;
import com.hongtech.tiny.modules.gen.vo.GenTableVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 代码生成器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/gen" )
public class GeneratorController {

    private final SysGeneratorService sysGeneratorService;

    /**
     * 列表
     */
    @RequestMapping("/list" )
    public ObjectResult<PageResult<GenTableVO>> list(
            @RequestParam String tableName,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        Page<GenTableVO> page = new Page<>(pageNum, pageSize);
        page.setOptimizeCountSql(false);
        return ObjectResult.success(sysGeneratorService.queryList(tableName, page));
    }

    /**
     * 生成代码
     */
    @RequestMapping("/code" )
    public void code(String tables, HttpServletResponse response) throws IOException {
        byte[] data = sysGeneratorService.generatorCode(tables.split("," ));
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"element-boot.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
